package org.linlinjava.litemall.admin.web;

import com.github.pagehelper.PageInfo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.admin.annotation.LoginAdmin;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallConfig;
import org.linlinjava.litemall.db.service.LitemallAdService;
import org.linlinjava.litemall.db.service.LitemallConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/config")
public class AdminConfigController {
    private final Log logger = LogFactory.getLog(AdminConfigController.class);

    @Autowired
    private LitemallAdService adService;

    @Autowired
    private LitemallConfigService configService;

    @GetMapping("/list")
    public Object list(
        @LoginAdmin Integer adminId,
        @RequestParam(value = "page", defaultValue = "1") Integer page,
        @RequestParam(value = "limit", defaultValue = "10") Integer limit,
        String sort,
        String order) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }

        List<LitemallConfig> configList = configService.querySelective(page, limit, sort, order);
        long total = PageInfo.of(configList).getTotal();
        Map<String, Object> data = new HashMap<>(2);
        data.put("total", total);
        data.put("items", configList);

        return ResponseUtil.ok(data);
    }

    @PostMapping("/update")
    public Object update(@LoginAdmin Integer adminId, @RequestBody LitemallConfig config) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        configService.updateById(config);
        return ResponseUtil.ok(config);
    }

    @PostMapping("/delete")
    public Object delete(@LoginAdmin Integer adminId, @RequestBody LitemallConfig config) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        configService.deleteById(config.getId());
        return ResponseUtil.ok();
    }

}
